package com.codef.sharp.common.core.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Objects;

/**
 * 获取请求工具
 * @author zhanrf
 * @date 2022/2/13 19:01
 */
public class RequestUtil {

	/**
	 * 获取请求体
	 * @return ServletRequest
	 */
	public static ServletRequest getRequest() {
		ServletRequestAttributes requestAttributes = getRequestAttributes();
		if (Objects.nonNull(requestAttributes)) {
			return requestAttributes.getRequest();
		}
		return null;
	}

	/**
	 * 获取响应体体
	 * @return ServletResponse
	 */
	public static ServletResponse getResponse() {
		ServletRequestAttributes requestAttributes = getRequestAttributes();
		if (Objects.nonNull(requestAttributes)) {
			return requestAttributes.getResponse();
		}
		return null;
	}

	public static ServletRequestAttributes getRequestAttributes() {
		return  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
	}
}
